import random
import time

from DrissionPage import SessionPage, ChromiumOptions, SessionOptions, Chromium
from email_permission import email_list
from logger import log_message, log_to_file
import json
import requests
import datetime

def open_account_palt_form(browser, account_id, result_text=None):
    account_tab = browser.new_tab('https://partner.xiaohongshu.com/partner/subAccount-list')
    # 加一个校验步骤， 不是叁柒的所属邮箱直接驳回
    account_tab.ele('tag:span@@class=d-text --color-static --color-text-paragraph --size-text-paragraph text label@@text()^登陆邮箱：').next().child().next().click(by_js=True)
    account_tab.wait(0.5)
    

    email_str = account_tab.ele('tag:span@@class=d-text --color-static --color-text-paragraph --size-text-paragraph text label@@text()^登陆邮箱：').next().child().text
    email_permission_list = email_list(result_text)

    # 用户名 ， 用于后面@人
    username = account_tab.ele('tag:span@@class=d-text --color-static --color-text-paragraph --size-text-paragraph text label@@text()^用户名：').next().text
    if email_str not in email_permission_list:
        log_message(result_text, f"当前邮箱账号:【{email_str}】暂无权限使用", "red")
        return

    account_tab.ele('tag:input@@class=el-input__inner@@type=text@@autocomplete=off@@placeholder=请输入').click()
    account_tab.ele('tag:input@@class=el-input__inner@@type=text@@autocomplete=off@@placeholder=请输入').input(account_id)
    account_tab.ele('tag:button@@id=search-btn--1').click(by_js=True)

    account_tab.wait(2)

    account_name = account_tab.ele(f'tag:div@@class=cell delight-tooltip@@text()={account_id}').parent(4).prev().ele('.cell delight-tooltip').text

    search_none_ele = account_tab.ele('tag:tr@@class=d-table__empty-row@@text()=暂无数据', timeout=0.5)
    if search_none_ele:
        log_message(result_text, f"合作伙伴平台子账号ID:{account_id}搜索结果为空, 检查表格第一行子账号ID, 或者检查是否登录合作伙伴平台", "red")
        return

    account_tab.ele('tag:span@@text():跳转', timeout=2).hover()
    jg_ele = account_tab.ele('tag:span@@class=d-text --color-static --color-current --size-text-paragraph d-text-nowrap d-text-ellipsis@@text():聚光平台', timeout=2)

    create_plan_tab = jg_ele.click.for_new_tab(by_js=True)
    create_plan_tab.wait.title_change("计划列表")
    return create_plan_tab, username, account_name


def get_today_date():
    today = datetime.date.today()
    return today.strftime("%Y-%m-%d")

def load_url(account_id, result_text=None, unit_dict_cookie=None):
    url = "https://ad.xiaohongshu.com/api/leona/rtb/unit/search"

    today_str = get_today_date()

    headers = {
        "accept": "application/json, text/plain, */*",
        "accept-language": "zh-CN,zh;q=0.9",
        "content-type": "application/json",
        "origin": "https://ad.xiaohongshu.com",
        "priority": "u=1, i",
        "referer": f"https://ad.xiaohongshu.com/aurora/ad/manage/unit?vSellerId={account_id}",
        "sec-ch-ua": '"Google Chrome";v="135", "Not-A.Brand";v="8", "Chromium";v="135"',
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": '"Windows"',
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36",
        "v-seller-id": account_id,
    }

    data_template = {
        "startTime": today_str,
        "endTime": today_str,
        "id": '',
        "pageNum": 1,
        "pageSize": 40
    }
    budget_insufficient_list = []
    data_dict = {}
    page = 1
    while True:
        data = data_template.copy()
        data["pageNum"] = page
        payload = json.dumps(data, separators=(',', ':'))

        try:
            response = requests.post(url, headers=headers, cookies=unit_dict_cookie, data=payload)
            response.raise_for_status()  # 抛出异常如果响应状态码不是2xx

            res_json = response.json()
            unit_data = res_json.get('data', {})

            total_page = unit_data.get('totalPage', 0)
            data_list = unit_data.get('list', [])

            log_message(result_text, f'共爬取到全部单元: {unit_data.get("total", 0)} 条，'
                                     f'页数: {total_page} 页, '
                                     f'当前正在处理第 {page} 页, '
                                     f'{len(data_list)} 条数据')

            for item in data_list:
                unit_id = item.get('unitId')
                if not unit_id:
                    continue  # 跳过没有 unitId 的数据

                unit_filter_state = item.get('unitFilterState')

                event_bid = item.get('eventBid')
                fee = item.get('data', {}).get('fee')

                data_value_str = item.get('data', {}).get('dataValueJson')
                try:
                    data_value_dict = json.loads(data_value_str) if data_value_str else {}
                except json.JSONDecodeError:
                    data_value_dict = {}

                ti_user_price = data_value_dict.get('tiUserPrice') # 新增深度种草人群成本

                campaign_day_budget = item.get('campaignDayBudget')
                campaign_name = item.get('campaignName')
                campaign_id = item.get('campaignId')

                if unit_filter_state == 8:
                    budget_insufficient_list.append({
                        'campaign_id': campaign_id,
                        'campaign_name': campaign_name,
                        'campaign_day_budget': campaign_day_budget,
                        'accumulated_spend': fee,
                        'current_bid': event_bid
                    })

                data_dict[unit_id] = {
                    'campaignId': campaign_id,
                    'campaignName': campaign_name,
                    'campaignDayBudget': campaign_day_budget,
                    'fee': fee,
                    'eventBid': event_bid,
                    'tiUserPrice': ti_user_price
                }

            if page >= total_page:
                break

            page += 1
            time.sleep(random.randint(1,3))
        except requests.RequestException as e:
            log_message(result_text, f"❌ 请求失败: {e}", "red")
            break

    return data_dict, budget_insufficient_list

# if __name__ == '__main__':
#     co = ChromiumOptions(read_file=False)  # 不读取文件方式新建配置对象
#     so = SessionOptions(read_file=False)
#     browser = Chromium(addr_or_opts=co, session_options=so)
#
#     open_account_palt_form(browser, '5df0c4392bed43000117d8e8')